package com.guwu.compress_image_uploading.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


public class PhotoOrCropUtil {

    private static final int REQUEST_CAREMA = 1001;
    private static final int REQUEST_MULTI = 1002;
    private static final int REQUEST_SINGLE = 1003;
    private static final int PHOTO_REQUEST_CUT = 1004;

    private File tempFile = null;//临时图片
    private Uri imageUri = null;
    //多选时存放已选中的图片路径的list
    private ArrayList<String> selectList;
    private Context mContext;
    private PhotoOrCropListener mListener;
    //是否剪切图片
    private boolean isCrop = false;

    public PhotoOrCropUtil(Context context) {
        selectList = new ArrayList<>();
        mContext = context;
    }

    /**
     * 开启相册，用途：多选图片
     */
    public void openGalleryMuti(int maxsize) {
        Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxsize);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择
        if (selectList != null && selectList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, selectList);
        }
        ((Activity) mContext).startActivityForResult(intent, REQUEST_MULTI);
    }

    /**
     * 开启相册，用途：单选图片
     *
     * @param isCrop 剪切图片
     */
    public void openGallerySingle(boolean isCrop) {
        this.isCrop = isCrop;
        Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        ((Activity) mContext).startActivityForResult(intent, REQUEST_SINGLE);
    }

    /**
     * 开启拍照，用途：单选图片
     *
     * @param isCrop 剪切图片
     */
    public void openCamera(boolean isCrop) {
        this.isCrop = isCrop;
        createTempFile();
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        ((Activity) mContext).startActivityForResult(intent, REQUEST_CAREMA);
    }

    /**
     * 剪切图片，只对单张
     */
    private void crop(Uri uri) {
        createTempFile();
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        // 从文件中创建uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        ((Activity) mContext).startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_SINGLE) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                selectList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                for (String p : selectList) {
                    sb.append(p);
                }
                crop(Uri.parse("file://" + sb.toString()));
                imageUri = Uri.parse("file://" + sb.toString());
                try {
                    if (isCrop) {
                        crop(imageUri);
                    } else {
                        tempFile = new File(new URI(imageUri.toString()));
                        setCallbackData();
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            } else {
                mListener.onError("取消选择");
            }
        } else if (requestCode == REQUEST_CAREMA) {
            if (resultCode == ((Activity) mContext).RESULT_OK) {
                //拍照返回的数据
                imageUri = Uri.fromFile(tempFile);
                crop(Uri.fromFile(tempFile));
                if (isCrop) {
                    crop(imageUri);
                } else {
                    setCallbackData();
                }
            } else {
                mListener.onError("取消选择");
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (resultCode == ((Activity) mContext).RESULT_OK) {
                setCallbackData();
            } else {
                imageUri = null;
            }
        } else if (requestCode == REQUEST_MULTI) {
            if (data != null) {
                // 得到图片的全路径
                selectList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                mListener.onSuccess(getFileList());
            } else {
                mListener.onError("取消选择");
            }
        }
    }

    /**
     * 获取多选的图片列表，未做压缩
     *
     * @return
     */
    private List<File> getFileList() {
        List<File> files = new ArrayList<>();
        for (String path : selectList) {
            files.add(new File(path));
        }
        return files;
    }

    private void setCallbackData() {
        if (imageUri != null) {
            if (tempFile == null || tempFile.exists() == false) {
                mListener.onError("图片获取失败");
                return;
            }
            mListener.onSuccess(tempFile);
        }
    }

    /**
     * 请求上传图片前调用，压缩图片5kb
     *
     * @param file
     */
    public void compressPic(File file, CompressUtils.CompressFinishCallBack<File> callBack) {
        CompressUtils.getInstance().compress(mContext, 5, file, callBack);
    }

    public void compressPic(List<File> files, CompressUtils.CompressFinishCallBack<List<File>> callBack) {
        CompressUtils.getInstance().compress(mContext, 5, files, callBack);
    }

    /**
     * 创建临时文件
     *
     * @return
     */
    private void createTempFile() {
        tempFile = FileUtil.getDateFile(mContext);
    }

    public void setPhotoOrCropListener(PhotoOrCropListener listener) {
        mListener = listener;
    }

    public interface PhotoOrCropListener {
        void onSuccess(File file);

        void onSuccess(List<File> files);

        void onError(String error);
    }
}
